import { createRouter, createWebHistory } from 'vue-router';
import routes from './routes';
import { checkLogin } from '../functions/login';
import loading from '../utils/loading';
import { setUserInfo } from '../functions/userInfo';

const router = createRouter({
  history: createWebHistory(),
  routes,
});
// 导航守卫
router.beforeEach(async (to, from, next) => {
  loading.show();
  // 登录验证
  if (to.meta.notCheckLogin) {
    next();
  } else {
    // 验证token
    const res = await checkLogin();
    if (res != null && res.code >= 0) {
      setUserInfo(res.data);
      next();
    } else {
      next('/login');
    }
  }
});
router.afterEach(() => {
  loading.hide();
});

export default router;
